# 1.导入smtplib模块
import smtplib
# 导入email模块
from email.mime.text import MIMEText  # 纯文本，HTML
from email.mime.image import MIMEImage  # 图片
from email.mime.multipart import MIMEMultipart  # 多种组合内容
from email.mime.application import MIMEApplication
from email.header import Header  # 发信抬头


# 2.创建一个邮件发送对象
class SendEmails:
    # host=smtp_server(发信服务器)
    def __init__(self, from_addr, to_addr, password, smtp_server, smtp_port):
        self.from_addr = from_addr
        self.to_addr = to_addr
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.password = password

    def send_text_email(self, subject, content):
        msg = MIMEText(content, "plain")
        msg['From'] = Header(self.from_addr)
        msg['To'] = Header(self.to_addr)
        msg['Subject'] = Header(subject)

        # 初始化SMTP_SSL客户端，指定邮箱服务器和端口
        with smtplib.SMTP_SSL(host=self.smtp_server, port=self.smtp_port) as smtp:
            try:
                # 登录邮箱
                smtp.login(self.from_addr, self.password)
                # 发送邮件
                smtp.sendmail(self.from_addr, self.to_addr, msg.as_string())
                # 关闭连接
                smtp.quit()
                # 发送成功，打印信息
                print("邮件发送成功！")
            except smtplib.SMTPException as e:
                print(f"邮件发送失败！{e}")

    def send_image_email(self, subject, image_path, content):
        msg = MIMEMultipart()
        msg['From'] = Header(self.from_addr)
        msg['To'] = Header(self.to_addr)
        msg['Subject'] = Header(subject)

        # 添加文本内容（如果有）
        if content:
            text_part = MIMEText(content, "plain", "utf-8")
            msg.attach(text_part)

        # 读取图片文件并创建MIMEImage对象
        try:
            with open(image_path, 'rb') as file:
                image_data = file.read()
                image = MIMEImage(image_data)

                # 可选：设置Content-ID以便在HTML中引用图片
                # image.add_header('Content-ID', '<image1>')

                # 设置图片文件名
                image.add_header('Content-Disposition', 'attachment', filename=image_path.split('/')[-1])
                msg.attach(image)

            # 初始化SMTP_SSL客户端，指定邮箱服务器和端口
            with smtplib.SMTP_SSL(host=self.smtp_server, port=self.smtp_port) as smtp:
                # 登录邮箱
                smtp.login(self.from_addr, self.password)
                # 发送邮件
                smtp.sendmail(self.from_addr, self.to_addr, msg.as_string())
                # 关闭连接
                smtp.quit()
                # 发送成功，打印信息
                print("邮件发送成功！")
        except smtplib.SMTPException as e:
            print(f"邮件发送失败！{e}")

    def send_attachment_email(self, subject, attachment_path, content=""):
        """
        发送包含附件的电子邮件。

        参数:
        subject - 邮件主题。
        attachment_path - 附件文件路径。
        content - 可选的文本内容。
        """
        # 创建一个MIMEMultipart对象作为邮件容器
        msg = MIMEMultipart()
        msg['From'] = Header(self.from_addr)
        msg['To'] = Header(self.to_addr)
        msg['Subject'] = Header(subject)

        # 添加文本内容（如果有）
        if content:
            text_part = MIMEText(content, "plain", "utf-8")
            msg.attach(text_part)

        # 读取附件文件并创建MIMEApplication对象
        try:
            with open(attachment_path, 'rb') as file:
                attachment = MIMEApplication(file.read())
                # 设置附件文件名
                attachment.add_header('Content-Disposition', 'attachment', filename=attachment_path.split('/')[-1])
                msg.attach(attachment)

            # 发送邮件
            with smtplib.SMTP_SSL(host=self.smtp_server, port=self.smtp_port) as smtp:
                smtp.login(self.from_addr, self.password)
                smtp.sendmail(self.from_addr, self.to_addr, msg.as_string())
                print("附件邮件发送成功！")
        except Exception as e:
            print(f"附件邮件发送失败！{e}")

    def send_combined_email(self, subject, content="", image_paths=None, attachment_paths=None):
        # 发送包含文本、图片和附件的组合电子邮件。
        # 创建一个MIMEMultipart对象作为邮件容器
        msg = MIMEMultipart()
        msg['From'] = Header(self.from_addr)
        msg['To'] = Header(self.to_addr)
        msg['Subject'] = Header(subject)

        # 添加文本内容（如果有）
        if content:
            text_part = MIMEText(content, "plain", "utf-8")
            msg.attach(text_part)

        # 添加图片（如果有）
        if image_paths:
            for i, image_path in enumerate(image_paths):
                try:
                    with open(image_path, 'rb') as file:
                        image = MIMEImage(file.read())
                        # 设置Content-ID以便在HTML中引用图片
                        image.add_header('Content-ID', f'<image{i + 1}>')
                        # 设置图片文件名
                        image.add_header('Content-Disposition', 'inline', filename=image_path.split('/')[-1])
                        msg.attach(image)
                except Exception as e:
                    print(f"添加图片 {image_path} 失败: {e}")

        # 添加附件（如果有）
        if attachment_paths:
            for attachment_path in attachment_paths:
                try:
                    with open(attachment_path, 'rb') as file:
                        attachment = MIMEApplication(file.read())
                        # 设置附件文件名
                        attachment.add_header('Content-Disposition', 'attachment',
                                              filename=attachment_path.split('/')[-1])
                        msg.attach(attachment)
                except Exception as e:
                    print(f"添加附件 {attachment_path} 失败: {e}")

        # 发送邮件
        try:
            with smtplib.SMTP_SSL(host=self.smtp_server, port=self.smtp_port) as smtp:
                smtp.login(self.from_addr, self.password)
                smtp.sendmail(self.from_addr, self.to_addr, msg.as_string())
                print("组合邮件发送成功！")
        except Exception as e:
            print(f"组合邮件发送失败！{e}")


# 测试一下,纯文本
test_text = SendEmails(
    from_addr='1424594006@qq.com',
    to_addr='1928897031@qq.com',
    password='txctpeypmsbvgehb',
    smtp_server='smtp.qq.com',
    smtp_port=465
)
subject = "测试邮件"
content = "下班了！王宜开，一会买不买荔枝，怎么买？"
test_text.send_text_email(subject, content)
